import {globalConfig} from "@/config/globalConfig";

let {baseUrl} = globalConfig
const uploadUrl = baseUrl + '/api/common/upload'
// const viewUrl = baseUrl + '/profile'
const viewUrl = baseUrl + '/api/common/static'

/**
 * 获取文件服务访问路径
 * @param url 文件路径
 * @returns {*|string}
 */
function getFileAccessHttpUrl(avatar, subStr) {
  /* if (url === undefined || url === null){
        return url
    }
    if (url.startsWith('http') || url.startsWith('https')){
        return url
    }
	 return viewUrl + "/" + url */
	 if (!subStr) subStr = 'http'
	 if (avatar && avatar.startsWith(subStr)) {
	     return avatar;
	 } else {
	     if (avatar && avatar.length > 0 && avatar.indexOf('[') === -1) {
	         return viewUrl + "/" + avatar;
	     }
	 }
}

/**
 * 封装一下 uni.request()
 * @param url
 * @param param
 * @param token
 * @returns {Promise<unknown>}
 */
async function getAction(url, param, token = uni.getStorageSync('token')) {
    try {
        const [err, res] = await uni.request({
            url: getUrl(url),
            data: param,
            method: 'GET',
            header: {
                'Authorization': token //自定义请求头信息
            },
        })
        if (err !== null) {
            return Promise.reject("请求失败")
        }
        // 请求成功
        return Promise.resolve(res.data)
    } catch (e) {
        return Promise.reject("请求异常")
    }
}

// getAction 更简洁
async function getActionSimple(url, param) {
    try {
        let res = await getAction(url, param)
        let {success, result, message} = res
        if (success) {
            return Promise.resolve(result)
        }
        return Promise.reject(message)
    } catch (e) {
        return Promise.reject(e)
    }
}

async function postAction(url, data, token = uni.getStorageSync('token')) {
    try {
        const [err, res] = await uni.request({
            url: getUrl(url),
            data,
            method: 'POST',
            dataType: 'json',
            header: {
                'Authorization': token //自定义请求头信息
            },
        })
        if (err !== null) {
            return Promise.reject("请求失败")
        }
        // 请求成功
        return Promise.resolve(res.data)
    } catch (e) {
        return Promise.reject("请求异常")
    }
}

/**
 * 更方便的postAction
 * @param url
 * @param data
 * @returns {Promise<unknown>}
 */
async function postActionSimple(url, data){
    try {
        let res = await postAction(url, data)
        let {result, message, success} = res
        if (success) {
            return Promise.resolve(result)
        }
        return Promise.reject(message)
    } catch (e) {
        return Promise.reject(e)
    }
}

/**
 * 文件上传
 *
 * @param path
 * @returns {Promise<*>}
 */
async function uploadAction(path) {
    let [err, res] = await uni.uploadFile({
        url: uploadUrl,
        filePath: path,
        name: 'file',
        header: {
            'Authorization': uni.getStorageSync('token') //自定义请求头信息
        },
        formData:{
            biz:'wechat'
        }
    })
    if (err) {
        return Promise.reject(err)
    }
    let data = JSON.parse(res.data)
    let {code ,msg} = data
    if (code !== 200){
        return Promise.reject(msg)
    }
    return Promise.resolve(msg)
}

/**
 * 选择图片.默认选择1张,选择一张时直接返回该张的图片地址(本地)
 * @param imgNumber
 * @param config
 * @returns {Promise<*>}
 */
export async function chooseImage(imgNumber = 1,config){
    let param = {
        count: imgNumber, //默认
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], //从相册选择
    }
    let [err,res] = await uni.chooseImage({...param,...config})
    if (err){
        return Promise.reject(err)
    }
    let {tempFilePaths} = res
    //只上传一张照片时,为了方便.直接获取地址
    if (imgNumber === 1){
        return tempFilePaths[0]
    }
    return tempFilePaths

}

/**
 * 根据传入url获取 要请求的地址
 * @param url 传入的url
 * @returns {*|string}
 */
function getUrl(url){
    if (url.startsWith("http") || url.startsWith("https")){
        return url
    }
    return url.startsWith('/') ? baseUrl + url : baseUrl + '/' + url
}

export  {
    getAction,
    getActionSimple,
    postAction,
    postActionSimple,
    getFileAccessHttpUrl,
    uploadAction,
    uploadUrl
}
